package net.cathackers.devel.scmp.chat.impl.xmpp.messageComponent;

import net.cathackers.devel.scmp.chat.impl.xmpp.iqcomponent.interfaces.Processor;
import net.cathackers.devel.scmp.chat.interfaces.ChatManager;
import net.cathackers.devel.scmp.factories.SCMPFactory;
import net.cathackers.devel.scmp.xmpp.MessagePacket;
import net.cathackers.devel.scmp.xmpp.Packet;
import net.cathackers.devel.scmp.xmpp.StanzaErrors;

public class OfflineDeliveryProcessor implements Processor<Packet> {
    private OfflineMessageStore messageStore_;
    private ChatManager chatManager_;

    public OfflineDeliveryProcessor(OfflineMessageStore store) {
	this.chatManager_  = SCMPFactory.getChatManager();
	this.messageStore_ = store;
    }

    public void process(Packet packet) {
	if (packet instanceof MessagePacket) {
	    MessagePacket messagePacket = (MessagePacket) packet;
	    if (messagePacket.getBody() != null) {
		try {
		    switch (messagePacket.getMessageType()) {
		    case normal:
		    case chat:
			messageStore_.storeOfflineMessage(messagePacket);
			break;
		    default:
			// drop the packet
			return;
		    }
		} catch (OfflineStoreIsFullException e) {
		    // return service unavailable error to the sender
		    MessagePacket errorPacket = getError(messagePacket);
		    chatManager_.deliverToUser(errorPacket);
		}
	    } else {
		return;
	    }

	}

    }

    private MessagePacket getError(MessagePacket packet) {
	StanzaErrors error = new StanzaErrors(
		StanzaErrors.Condition.service_unavailable);
	packet.setError(error);
	packet.setTo(packet.getFrom());
	// TODO setFrom(ServerDomain);
	packet.setFrom(null);
	return packet;
    }
}
